using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Deepcode.Flux.Core.Systems.Scheduler;
using Deepcode.Flux.Core.Services.State;
using Deepcode.Flux.Core.Extensions;
using Deepcode.Flux.Core.Systems.Audit.Quick;

public partial class Private_Config_Scheduled_ui_Form : Deepcode.Flux.Core.UI.AdministrationModulePage
{
	#region Permission Code Override
	public override string RequiredPermissionCode { get { return "FluxGeneralAdmin"; } }
	#endregion
	#region ViewState storage
	/// <summary>
	/// Stores the state of the listing view
	/// </summary>
	public string ListingState
	{
		get
		{
			return (string)ViewState["ListingState"];
		}
		set
		{
			ViewState["ListingState"] = value;
		}
	}
	/// <summary>
	/// Stores the ID of the record being edited
	/// </summary>
	public int RecordID
	{
		get
		{
			object o = ViewState["RecordID"];
			if (o == null) return -1;
			return (int)o;
		}
		set
		{
			ViewState["RecordID"] = value;
		}
	}
	#endregion
	#region Page Load Event
	/// <summary>
	/// Page Load event
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			// Store any state information from the calling listing
			this.ListingState = GetAttribute("state", "");
			this.RecordID = GetAttribute("ID", -1);

			// Load the record if specified
			if (this.RecordID != -1)
			{
				Tasks tasks = new Tasks();
				Task  task = tasks.GetTaskByID( this.RecordID );
				if( task == null ) GoBack();

				TaskName.Text = task.TaskName;
				ExecuteNext.Text = task.ExecuteNext.ToString("dd MMM yyyy HH:mm");
				Finished.Checked = task.Finished;
				Frequency.SelectedValue = ((int) task.Frequency).ToString();
				Interval.Text = task.Interval.ToString();
				TimesRemaining.Text = task.TimesRemaining.ToString();
				Execute.Text = task.Execute;
				TaskExpires.Checked = task.TaskExpires;
				ExpireTask.Text = task.ExpireTask.ToString("dd MMM yyyy HH:mm");

				RunOnce.Checked = (task.Frequency == TaskFrequency.OnceOnly);
				RunSchedule.Checked = !RunOnce.Checked;

				TimesUnlimited.Checked = (task.TimesRemaining == -1);

				SetFormState();
			}
		}
	}
	#endregion
	#region Navigation
	/// <summary>
	/// Returns to the listing, restoring state
	/// </summary>
	protected void GoBack()
	{
		string url = String.Format("default.aspx?state={0}", this.ListingState);
		Response.Redirect(url, true);
	}
	#endregion
	#region Save/Cancel handlers
	/// <summary>
	/// User cancelled the save, go back to previous page
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnCancel_Click(object sender, EventArgs e)
	{
		GoBack();
	}
	/// <summary>
	/// User clicked the save button, store the data
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void btnSave_Click(object sender, EventArgs e)
	{
		if (!Page.IsValid) return;

		Tasks tasks = new Tasks();
		Task task = null;
		if (RecordID == -1)
			task = new Task();
		else
			task = tasks.GetTaskByID( RecordID );

		if( task == null ) GoBack();
		
		task.TaskName = TaskName.Text;
		task.Execute = Execute.Text;
		task.ExecuteNext = ExecuteNext.DateTimeValue;
		task.Finished = Finished.Checked;
		if (RunOnce.Checked)
		{
			task.Frequency = TaskFrequency.OnceOnly;
			task.Interval = 1;
			task.TimesRemaining = -1;
			task.TaskExpires = false;
			task.ExpireTask = System.DateTime.Now;
		}
		else
		{
			task.Frequency = (TaskFrequency) (Int32.Parse(Frequency.SelectedValue));
			task.Interval = (Int32.Parse(Interval.Text));
			if (TimesUnlimited.Checked)
				task.TimesRemaining = -1;
			else
				task.TimesRemaining = (Int32.Parse(TimesRemaining.Text));

			task.TaskExpires = TaskExpires.Checked;
			if( task.TaskExpires )
				task.ExpireTask = ExpireTask.DateTimeValue;
			else
				task.ExpireTask = System.DateTime.Now;
		}

		tasks.Save( task );

		QuickAudit.RaiseImportant(
			new AuditUser(),
			"Flux", "Scheduled Tasks",
			"created/modified scheduled task ({0})", task.TaskName);


		GoBack();
	}
	#endregion

	#region OnInit
	protected override void OnInit(EventArgs e)
	{
		base.OnInit(e);
		RunOnce.CheckedChanged += new EventHandler(FormUpdate);
		RunSchedule.CheckedChanged += new EventHandler(FormUpdate);
		TimesUnlimited.CheckedChanged += new EventHandler(FormUpdate);
		TaskExpires.CheckedChanged += new EventHandler(FormUpdate);

		ValidateIntervalSet.ServerValidate += new ServerValidateEventHandler(ValidateIntervalSet_ServerValidate);
		ValidateTimesRemaining.ServerValidate += new ServerValidateEventHandler(ValidateTimesRemaining_ServerValidate);
		ValidateExpiry.ServerValidate += new ServerValidateEventHandler(ValidateExpiry_ServerValidate);
	}
	#endregion
	#region SetFormState - sets the state of the form based on selections
	
	void FormUpdate(object sender, EventArgs e)
	{
		SetFormState();
	}
	
	private void SetFormState()
	{
		if( RunOnce.Checked ) PanelSchedule.Visible = false;
		if (!RunOnce.Checked)
		{
			PanelSchedule.Visible = true;
			if( TimesUnlimited.Checked == true ) PanelUnlimitedRuns.Visible = false;
			else PanelUnlimitedRuns.Visible = true;

			if( TaskExpires.Checked == true ) PanelExpiry.Visible = true;
			else PanelExpiry.Visible = false;
		}
	}
	#endregion
	#region Custom validation
	void ValidateExpiry_ServerValidate(object source, ServerValidateEventArgs args)
	{
		if (TaskExpires.Checked)
		{
			if (ExpireTask.Text == "") args.IsValid = false;
			else
			{
				try
				{
					DateTime dt = DateTime.Parse(ExpireTask.Text);
					args.IsValid = true;
				}
				catch
				{
					args.IsValid = false;
				}
			}
		}
		else
		{
			args.IsValid = true;
		}
	}

	void ValidateTimesRemaining_ServerValidate(object source, ServerValidateEventArgs args)
	{
		if (TimesUnlimited.Checked == false)
		{
			if (TimesRemaining.Text == "") args.IsValid = false;
			else
			{
				try
				{
					int x = Int32.Parse(TimesRemaining.Text);
					args.IsValid = true;
				}
				catch
				{
					args.IsValid = false;
				}
			}
		}
		else
			args.IsValid = true;
	}

	void ValidateIntervalSet_ServerValidate(object source, ServerValidateEventArgs args)
	{
		if (RunSchedule.Checked)
		{
			if (Interval.Text == "") args.IsValid = false;
			else
			{
				try
				{
					int x = Int32.Parse(Interval.Text);
					args.IsValid = true;
				}
				catch
				{
					args.IsValid = false;
				}
			}
		}
		else
			args.IsValid = true;
	}
	#endregion
}
